#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from common import common
from common.common_models import ActionResult
from common.const import ExecuteResultEnum, CMDResult, JsonProperty
from common.logger import Logger
from db2.backup.util.ha_utils import is_power_rhel_ha
from db2.comm.const import Db2Const

LOGGER = Logger().get_logger(filename="db2.log")


class DpfBackupUtil:
    """
    DPF集群备份工具类
    """
    @staticmethod
    def is_dpf_cluster(param_dict):
        """判断是否DPF集群"""
        cluster_type = param_dict.get(JsonProperty.JOB, {}).get(JsonProperty.PROTECTENV, {}).\
            get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        if not cluster_type:
            cluster_type = param_dict.get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        if not cluster_type:
            cluster_type = param_dict.get(JsonProperty.APPENV, {}).\
                get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        return cluster_type == Db2Const.DPF_CLUSTER_TYPE

    @staticmethod
    def is_hadr_cluster(param_dict):
        """判断是否HADR集群"""
        cluster_type = param_dict.get(JsonProperty.JOB, {}).get(JsonProperty.PROTECTENV, {}).\
            get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        if not cluster_type:
            cluster_type = param_dict.get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        if not cluster_type:
            cluster_type = param_dict.get(JsonProperty.APPENV, {}).\
                get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        return cluster_type == Db2Const.HADR

    @staticmethod
    def is_ha_cluster(param_dict):
        """判断是否HA集群"""
        cluster_type = param_dict.get(JsonProperty.JOB, {}).get(JsonProperty.PROTECTENV, {}).\
            get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        if not cluster_type:
            cluster_type = param_dict.get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        if not cluster_type:
            cluster_type = param_dict.get(JsonProperty.APPENV, {}).\
                get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        if not cluster_type:
            cluster_type = param_dict.get(JsonProperty.JOB, {}).get(JsonProperty.TARGETENV, {}).\
                get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        return is_power_rhel_ha(cluster_type)

    @staticmethod
    def get_cluster_type(param_dict):
        """判断是否HA集群"""
        cluster_type = param_dict.get(JsonProperty.JOB, {}).get(JsonProperty.PROTECTENV, {}).\
            get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        if not cluster_type:
            cluster_type = param_dict.get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        if not cluster_type:
            cluster_type = param_dict.get(JsonProperty.APPENV, {}).\
                get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        if not cluster_type:
            cluster_type = param_dict.get(JsonProperty.JOB, {}).get(JsonProperty.TARGETENV, {}).\
                get(JsonProperty.EXTENDINFO, {}).get(JsonProperty.CLUSTERTYPE, "")
        return cluster_type

    @staticmethod
    def record_task_result(pid, err_msg, code=None, err_code=None):
        action_result = ActionResult(code=ExecuteResultEnum.INTERNAL_ERROR.value if code is None else code,
                                     message=err_msg)
        if err_code:
            action_result.body_err = err_code
        common.output_result_file(pid, action_result.dict(by_alias=True))

    @staticmethod
    def execute_ts_backup(ts_backup_cmd):
        backup_time = ""
        LOGGER.info(f"Starting backup table spaces, cmd: {ts_backup_cmd}.")
        return_code, out, err = common.execute_cmd(ts_backup_cmd)
        if return_code != CMDResult.SUCCESS.value:
            LOGGER.error(f"Execute backup table spaces command failed. return code: {return_code}, "
                         f"out: {out}, err: {err}.")
            raise Exception("Execute backup table spaces command failed")
        for line in out.split("\n"):
            if "The timestamp for this backup image is" in line:
                backup_time = line.split(":")[1].strip()
                break
        LOGGER.info(f"Execute backup table spaces command success, backup time: {backup_time}.")
        return backup_time
